import axios, { Method } from 'axios';
import { getUser, removeUser, getResourceCode } from '@/utils/user-util';
import { Message } from 'element-ui';
import { isIframeContent } from '@/utils/portal-util';
import router from '@/router';
// eslint-disable-next-line camelcase
import { yh_message_error, yh_message_success, yh_message_warn } from '@yhfin/biz/components/yh-message';
import { getConfigItem } from './tools';

const baseUrl = getConfigItem('BASE_URL_API');

const request = axios.create({
    baseURL: baseUrl,
    timeout: 2000000,
});

interface IDownLoadFileOption {
    baseURL?: string;
    method?: Method;
    url?: string;
    data?: any;
    loading?: boolean;
    loadingMsg?: string;
    [propName: string]: any;
}

/**
 * 请求拦截器
 */
request.interceptors.request.use(
    config => {
        if (config.headers && !config.headers['Authentication']) {
            config.headers['Authentication'] = getUser().sessionId;
        }
        if (config.headers && !config.headers['Resource-Code']) {
            config.headers['Resource-Code'] = getResourceCode(window.location.href);
        }
        if (config.headers) {
            // 操作类型用于设置系统日志类型 autoRefresh:定时刷新，userAction：人为点击操作；operateType为空时默认为userAction;
            if (!config.headers['operateType']) {
                config.headers['operateType'] = 'userAction';
            } else {
                config.headers['operateType'] = 'autoRefresh';
            }
        }
        config.baseURL = config.baseURL ? config.baseURL : baseUrl;
        config.timeout = config.timeout ? config.timeout : 2000000;
        return config;
    },
    error => {
        const errMsg: string = 'request error: ' + error.message;
        yh_message_error(errMsg);
        // Message.error(errMsg); // for debug
        return Promise.reject(errMsg);
    }
);

/**
 * 响应拦截器
 */
request.interceptors.response.use(
    (response: any): any => {
        if (response.status === 200) {
            const data = response.data;
            if (data.returnCode !== '000000') {
                if (data.returnCode === '000004') {
                    if (isIframeContent()) {
                        try {
                            removeUser();
                            if (getConfigItem('WEB_DOCKING') === 'MAXWEALTH' && window.location.pathname === '/YH/') {
                                // 当项目集成化且实现单点登录后 不应刷新上层跳转到login
                                // 集成化后 实际项目结构 构成为三层  项目集成系统 => RISK => iframe
                                // 实际表现为 内嵌在项目集成系统中的页面不断刷新
                            } else {
                                window.parent.location.reload();
                            }
                        } catch (e) {}
                        router.push('/error?msg=' + '登录状态已失效');
                    } else {
                        router.push({ path: '/login' });
                    }
                }
                yh_message_error(data.returnMsg);
                return Promise.reject(data.returnMsg);
            }
            return response.data.data;
        } else {
            yh_message_error(response['message']);
            return Promise.reject(response['message']);
        }
    },
    error => {
        const errMsg: string = 'request error: ' + error.message;
        yh_message_error(errMsg);
        return Promise.reject(errMsg);
    }
);

export default request;

export const showLoading = (): void => {
    const loading: HTMLElement = document.getElementById('custom-loading');
    if (loading) {
        loading.style.display = 'flex';
    }
};

export const hiddenLoading = (): void => {
    const loading: HTMLElement = document.getElementById('custom-loading');
    if (loading) {
        loading.style.display = 'none';
    }
};

export const downLoadFile = (option: IDownLoadFileOption) => {
    return new Promise((resolve, reject) => {
        const Authentication = getUser().sessionId;
        const baseURL = option.baseURL ? option.baseURL : baseUrl;
        let httpLoading;
        if (option.loading) {
            const loadingMsg = option.loadingMsg ? option.loadingMsg : ' 加载中 请稍后... ... ';
            httpLoading = Message({
                message: loadingMsg,
                duration: 0,
                iconClass: 'el-icon-loading',
                type: 'success',
                center: true,
            });
        }

        axios({
            method: option.method ? option.method : 'get',
            url: option.url,
            baseURL: baseURL,
            responseType: 'blob',
            data: option.data,
            headers: { Authentication: Authentication },
        })
            .then(response => {
                if ((response.headers['content-type'] || '').includes('application/json')) {
                    const reader = new FileReader();
                    reader.readAsText(response.data);
                    reader.onload = function(event) {
                        const content = JSON.parse(
                            <string>reader.result || '{}' // 内容就在这里
                        );
                        if (content.returnCode === '000000') {
                            yh_message_warn('导出失败,非文件格式,' + content.returnMsg);
                        } else {
                            yh_message_error('导出失败,' + content.returnMsg);
                        }
                    };
                    reject(new Error('ERROR'));
                    return;
                }
                let fileName = '';
                let value = '';
                try {
                    // 文件名使用后台默认的文件名
                    value = decodeURI(response.headers['content-disposition']);
                    fileName = value.split(';')[1].split('=')[1];
                } catch (e) {
                    // fileName = moment().format('YYYY-MM-DD') + '.xls'
                    yh_message_warn('导出失败,联系管理员！' + value);
                    reject(new Error('ERROR'));
                    return;
                }
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(
                    new Blob([response.data], {
                        type: response.headers['content-type'],
                    })
                );
                link.target = '_blank';
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve('SUCCESS');
            })
            .catch(error => {
                yh_message_error('ERROR：' + error.message);
                reject(new Error('ERROR'));
            })
            .finally(() => {
                if (option.loading) {
                    httpLoading.close();
                }
            });
    });
};

/**
 * 调用引擎下载接口
 */
export const downLoadFileEngine = (option: IDownLoadFileOption) => {
    return new Promise((resolve, reject) => {
        const Authentication = getUser().sessionId;
        // const baseURL = option.baseURL ? option.baseURL : baseUrl;
        let httpLoading;
        if (option.loading) {
            const loadingMsg = option.loadingMsg ? option.loadingMsg : ' 加载中 请稍后... ... ';
            httpLoading = Message({
                message: loadingMsg,
                duration: 0,
                iconClass: 'el-icon-loading',
                type: 'success',
                center: true,
            });
        }

        axios({
            method: option.method ? option.method : 'get',
            url: option.url,
            baseURL: option.baseURL,
            responseType: 'blob',
            data: option.data,
            headers: { Authentication: Authentication },
        })
            .then(response => {
                if ((response.headers['content-type'] || '').includes('application/json')) {
                    const reader = new FileReader();
                    reader.readAsText(response.data);
                    reader.onload = function(event) {
                        const content = JSON.parse(
                            <string>reader.result || '{}' // 内容就在这里
                        );
                        if (content.returnCode === '000000') {
                            yh_message_warn('导出失败,非文件格式,' + content.returnMsg);
                        } else {
                            yh_message_error('导出失败,' + content.returnMsg);
                        }
                    };
                    reject(new Error('ERROR'));
                    return;
                }
                let fileName = '';
                let value = '';
                try {
                    // 文件名使用后台默认的文件名
                    value = decodeURI(response.headers['content-disposition']);
                    fileName = value.split(';')[1].split('=')[1];
                } catch (e) {
                    // fileName = moment().format('YYYY-MM-DD') + '.xls'
                    yh_message_warn('导出失败,联系管理员！' + value);
                    reject(new Error('ERROR'));
                    return;
                }
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(
                    new Blob([response.data], {
                        type: response.headers['content-type'],
                    })
                );
                link.target = '_blank';
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve('SUCCESS');
            })
            .catch(error => {
                yh_message_error('ERROR：' + error.message);
                reject(new Error('ERROR'));
            })
            .finally(() => {
                if (option.loading) {
                    httpLoading.close();
                }
            });
    });
};

export const downLoadFileFormData = (option: IDownLoadFileOption) => {
    return new Promise((resolve, reject) => {
        const Authentication = getUser().sessionId;
        const baseURL = option.baseURL ? option.baseURL : baseUrl;
        let httpLoading;
        if (option.loading) {
            const loadingMsg = option.loadingMsg ? option.loadingMsg : ' 加载中 请稍后... ... ';
            httpLoading = Message({
                message: loadingMsg,
                duration: 0,
                iconClass: 'el-icon-loading',
                type: 'success',
                center: true,
            });
        }

        axios({
            method: option.method ? option.method : 'get',
            url: option.url,
            baseURL: baseURL,
            responseType: 'blob',
            data: option.data,
            headers: { Authentication: Authentication, 'Content-Type': 'multipart/form-data' },
        })
            .then(response => {
                console.log(response, 'response');
                if ((response.headers['content-type'] || '').includes('application/json')) {
                    const reader = new FileReader();
                    reader.readAsText(response.data);
                    reader.onload = function(event) {
                        const content = JSON.parse(
                            <string>reader.result || '{}' // 内容就在这里
                        );
                        console.log(content, 'content');
                        if (content.returnCode === '000000') {
                            yh_message_warn('导出失败,非文件格式,' + content.returnMsg);
                            // Message.warning('导出失败,非文件格式,' + content.returnMsg);
                        } else {
                            yh_message_error('导出失败,' + content.returnMsg);
                            // Message.error('导出失败,' + content.returnMsg);
                        }
                    };
                    reject(new Error('ERROR'));
                    return;
                }
                let fileName = '';
                let value = '';
                try {
                    // 文件名使用后台默认的文件名
                    value = decodeURI(response.headers['content-disposition']);
                    fileName = value.split(';')[1].split('=')[1];
                } catch (e) {
                    // fileName = moment().format('YYYY-MM-DD') + '.xls'
                    yh_message_warn('导出失败,联系管理员！' + value);
                    // Message.error('导出失败,联系管理员！' + value);
                    reject(new Error('ERROR'));
                    return;
                }
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(
                    new Blob([response.data], {
                        type: response.headers['content-type'],
                    })
                );
                link.target = '_blank';
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve('SUCCESS');
            })
            .catch(error => {
                yh_message_error('ERROR：' + error.message);
                // Message.error('ERROR：' + error.message);
                reject(new Error('ERROR'));
            })
            .finally(() => {
                if (option.loading) {
                    httpLoading.close();
                }
            });
    });
};

/**
 * 下载文件流 用于预览
 */
export const downloadBlob = (option: IDownLoadFileOption) => {
    return new Promise((resolve, reject) => {
        const Authentication = getUser().sessionId;
        const baseURL = 'http://192.168.75.57:9095/yhfin/risk/web';
        let httpLoading;
        if (option.loading) {
            const loadingMsg = option.loadingMsg ? option.loadingMsg : ' 加载中 请稍后... ... ';
            httpLoading = Message({
                message: loadingMsg,
                duration: 0,
                iconClass: 'el-icon-loading',
                type: 'success',
                center: true,
            });
        }

        axios({
            method: option.method ? option.method : 'get',
            url: option.url,
            baseURL: baseURL,
            responseType: 'blob',
            data: option.data,
            headers: { Authentication: Authentication },
        })
            .then(response => {
                if ((response.headers['content-type'] || '').includes('application/json')) {
                    const reader = new FileReader();
                    reader.readAsText(response.data);
                    reader.onload = function(event) {
                        const content = JSON.parse(
                            <string>reader.result || '{}' // 内容就在这里
                        );
                        if (content.returnCode === '000000') {
                            yh_message_warn('导出失败,非文件格式,' + content.returnMsg);
                        } else {
                            yh_message_error('导出失败,' + content.returnMsg);
                        }
                    };
                    reject(new Error('ERROR'));
                    return;
                }
                let fileName = '';
                let value = '';
                try {
                    // 文件名使用后台默认的文件名
                    value = decodeURI(response.headers['content-disposition']);
                    fileName = value.split(';')[1].split('=')[1];
                } catch (e) {
                    // fileName = moment().format('YYYY-MM-DD') + '.xls'
                    yh_message_warn('导出失败,联系管理员！' + value);
                    reject(new Error('ERROR'));
                    return;
                }

                resolve(response.data);
            })
            .catch(error => {
                yh_message_error('ERROR：' + error.message);
                reject(new Error('ERROR'));
            })
            .finally(() => {
                if (option.loading) {
                    httpLoading.close();
                }
            });
    });
};
